from sqlalchemy import create_engine, text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine.url import make_url
from config import settings

def _ensure_mysql_database_exists(database_url: str) -> None:
    """在使用 MySQL 时，若目标数据库不存在则自动创建。
    仅当 backend 使用 mysql 方言时生效。
    """
    url = make_url(database_url)
    if url.get_backend_name() != "mysql":
        return

    database_name = url.database
    if not database_name:
        return

    # 连接到不指定数据库的 MySQL 服务器
    server_url = url.set(database=None)
    engine_no_db = create_engine(server_url, pool_pre_ping=True)
    with engine_no_db.connect() as conn:
        conn.execute(
            text(
                f"CREATE DATABASE IF NOT EXISTS `{database_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
            )
        )
        conn.commit()

# 若是 MySQL，确保数据库已存在
_ensure_mysql_database_exists(settings.DATABASE_URL)

# 创建数据库引擎
engine = create_engine(
    settings.DATABASE_URL,
    pool_pre_ping=True,
    echo=settings.DEBUG
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基础模型类
Base = declarative_base()

def get_db():
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
